<?php

namespace app\mobile\controller;

use app\common\controller\Platurl;
use app\common\model\CardCzgive;
use app\common\model\CardCzLog;
use app\common\model\CardGoods;
use app\common\model\CardMember;
use app\common\model\CardOrder;
use app\common\model\CardUserGet;
use app\common\model\CardRank;
use app\common\model\Agent;
use app\common\model\CardUserUpdate;
use app\common\model\MerchantContent;
use app\common\model\Momerchant;
use app\common\model\Paylog;
use app\common\model\WxOpen;
use app\common\model\Merchant;
use app\common\model\System;
use app\common\validate\LoginUsers;
use think\Controller;
use think\Request;
use think\Session;
use Wechat\Wxobjopen;

class Testuser extends Controller
{


    public function testgetopenid(){
        $Platurl = new Platurl();
        $option = $Platurl->getagenttplmsg(1);
        $WxObj = new Wxobjopen($option);
        $info = $WxObj->getOpenoauthAccessToken();
        if (!$info) {
            $callback = 'https://' . $_SERVER ['SERVER_NAME'] . url("testuser/testgetopenid");
            $url = $WxObj->getopenOauthRedirect($callback, '', 'snsapi_base');
            header("Location: $url");
            exit();
        } else {
            $openid = $info['openid'];
            $openuserinfo = $WxObj->getUserInfo($openid);
            var_dump(json_encode($openuserinfo,JSON_UNESCAPED_UNICODE));
            exit();
//                file_put_contents('/data2/html/payos/test.txt', 'login-3' . json_encode($openuserinfo,JSON_UNESCAPED_UNICODE), FILE_APPEND);
            if($openuserinfo['subscribe']==0){
                return $this->fetch('guanzhu');
            }
        }
    }

    // array('scode' => request()->param('scode'), 'id' => request()->param('id'))

    public function getcards(){
        $arr = request()->param();
        $card['card_id'] = $arr['card_id'];
        $this->assign('card',$card);
        return $this->fetch();
    }

    public function themachcard(){
        $arr = request()->param();
        $card['card_id'] = $arr['card_id'];
        $this->assign('card',$card);
        return $this->fetch();
    }

    /*
     * 首页
     * $card_id
     *
     */
    public function index()
    {
        //获取传值
        $arr = request()->param();
        //解密code 获取用户信息
        if (isset($arr['encrypt_code'])){
            $this->getusercode($arr);
        }
        //获取授权
        $this->_init();
        $appid = $this->getappid($arr['card_id']);
        $info = $this->getuserinfo($arr);
        //不存在符合条件的则跳转到投放页面
        if (empty($info)) {
            $data['card_id'] = $arr['card_id'];
            $data['openid'] = Session::get($appid.'_openid');
            $this->redirect('Carduser/addcard', $data);
        } else {
            $CardUserGet = new CardUserGet();
            $info['balance'] = sprintf("%.2f", $info['balance']);
            $maps['card_id'] = $arr['card_id'];
            if ($info['qrcode'] == ''){
                $userinfo['qrcode'] = $this->qrcode($info['code']);
                $CardUserGet->save($userinfo,['id'=>$info['id']]);
            }
            $CardMember = new CardMember();
            $card = $CardMember->where($maps)->find();
            $this->assign('card', $card);       //ka
            $this->assign('info', $info);       //user
            $jssdk['type'] = 0;
            $this->assign('jssdk', $jssdk);
            return $this->fetch();
        }
    }

    //在线充值
    /* 查询该会员卡的信息支付时用作传入参数
     *
     */
    //在线充值
    /* 查询该会员卡的信息支付时用作传入参数
     *
     */
    public function recharge()
    {
        $appid = $this->getappid(request()->param('card_id'));
        if (Request()->isAjax()) {
            $arr = request()->param();
//            return json($arr);
            if ($this->getpaystatu($arr) == 1) {
                if (Request()->post('price') > 0) {
                    $Merchant = new Merchant();
                    $Agent = new Agent();
                    $WxOpen = new WxOpen();
                    $map['id'] = Request()->post('mid');
                    $config = $Merchant->where($map)->find();
                    $agent = $Agent->where(array('id' => $config['agent']))->find();
                    $users = $WxOpen->where(array('id' => $agent['wx_open_id']))->find();
                    $userwx = $WxOpen->where(array('id' => $config['wx_open_id']))->find();

                    $options = array(
                        'appid' => $users['authorizer_appid'], // 填写高级调用功能的app id
                        'partnerid' => $agent['partnerid'], // 财付通商户身份标识
                        'partnerkey' => $agent['partnerkey'], // 财付通商户权限密钥Key
                    );
//                return json($options);
                    $weObj = new Wxobjopen($options);
                    $price = request()->post('price');
                    $appid = $users['authorizer_appid'];
                    $mch_id = $agent['partnerid'];
                    $out_trade_no = request()->post('orderid');
                    $body = "会员卡充值";
                    $sub_mch_id = $config['sub_mch_id'];
                    $sub_appid = $userwx['authorizer_appid'];
                    $total_fee = $price * 100;
                    $data['orderid'] = $out_trade_no;
                    $data['mid'] = request()->post('mid');
                    $data['openid'] = request()->post('openid');
                    $data['pay_statu'] = 0;
                    $data['price'] = $price;
                    $data['yf_price'] = $price;
                    $data['zk_price'] = $data['yf_price'] - $data['price'];
                    $data['add_time'] = time();
                    $data['attach'] = 'cardcz';
                    $data['cz_card_id'] = request()->post('cardid');
                    $CardCzLog = new CardCzLog();
                    $CardCzgive = new CardCzgive();
                    $giveid = request()->post('giveid');
                    $czdata['openid'] = request()->post('openid');
                    $czdata['card_get_id'] = $data['cz_card_id'];
                    $czdata['code'] = getcardcode_getid($data['cz_card_id']);
                    $czdata['cz_price'] = $price;
                    $czdata['zs_price'] = $CardCzgive->where('id', $giveid)->value('zs_money');
                    $czdata['orderid'] = $out_trade_no;
                    $czdata['giveid'] = $giveid;
                    $czdata['addtime'] = time();
                    $c = $CardCzLog->allowField(true)->save($czdata);
                    $Paylog = new Paylog();
                    $add = $Paylog->allowField(true)->save($data);
                    $sub_openid = Session::get('card_openid');
                    $notify_url = 'https://' . $_SERVER ['SERVER_NAME'] . '/api.php';
                    $spbill_create_ip = $_SERVER["REMOTE_ADDR"];
                    $nonce_str = $weObj->generateNonceStr();
                    $pay_xml = $weObj->createPackageXml2($appid, $sub_appid, $mch_id, $sub_mch_id, $nonce_str, $body, $out_trade_no, $total_fee, $spbill_create_ip, $notify_url, '', $sub_openid);
                    $pay_xml = $weObj->get_pay_id($pay_xml);
//                return json($pay_xml);
                    if ($pay_xml['return_code'] == 'SUCCESS') {
                        $prepay_id = $pay_xml['prepay_id'];
                        $jsApiObj["appId"] = $appid;
                        $timeStamp = time();
                        $jsApiObj["timeStamp"] = "$timeStamp";
                        $jsApiObj["nonceStr"] = $nonce_str;
                        $jsApiObj["package"] = "prepay_id=" . $prepay_id;
                        $jsApiObj["signType"] = "MD5";
                        $jsApiObj["paySign"] = $weObj->getPaySignature($jsApiObj);
                        //状态码
                        $jsApiObj['code'] = 0;
                    } else {
                        $jsApiObj = ['code' => 9002, 'message' => '支付失败！'];
                    }
                } else {
                    $jsApiObj = ['code' => 9001, 'message' => '请输入正确的充值金额！'];
                }
            }else{
                $jsApiObj = ['code' => 9003, 'message' => '充值失败！'];
            }
            return json($jsApiObj);
        } else {

            //获取传值
            $arr = request()->param();
            //解密code 获取用户信息
            if (isset($arr['encrypt_code'])){
                $this->getusercode($arr);
            }
            //获取授权
            $this->_init();
            $info = $this->getuserinfo($arr);

            //不存在符合条件的则跳转到投放页面
            if (empty($info)) {
                $data['card_id'] = $arr['card_id'];
                $data['openid'] = Session::get($appid.'_openid');
                $this->redirect('Carduser/addcard', $data);
            } else {
                $CardMember = new CardMember();
                $CardCzgive = new CardCzgive();
                $maps['card_id'] = $arr['card_id'];
                $maps['statu'] = 1;
                $czgive = $CardCzgive->where($maps)->select();
                $user['mid'] = $CardMember->where('card_id', $arr['card_id'])->value('mid');
                $user['openid'] = Session::get($appid.'_openid');
                $card = $CardMember->where(['card_id'=>$arr['card_id']])->field('title,is_cz_qtprice')->find();
                $this->assign('card',$card);
                $this->assign('user', $user);
                $this->assign('czgive', $czgive);
                $this->assign('info', $info);
                $CardMember = new CardMember();
                $is_zxcz = $CardMember->where('card_id', $arr['card_id'])->value('is_zxcz');
                if ($is_zxcz == 1) {
                    return $this->fetch();
                } else {
                    return $this->fetch('off');
                }
            }
        }
    }

    //检查支付提交
    private function getpaystatu($arr){
        //自定义
        if ($arr['giveid'] == ''){
            if ($arr['givetype'] == 'custom'){
                $res = 1;
            }else{
                $res = 2;
            }
        }else{
            //规则充值
            if ($arr['givetype'] == 'giverule'){
                $res = 1;
            }else{
                $res = 2;
            }
        }
        return $res;
    }

    /*
     * 支付结束
     *
     */
    public function r_payover()
    {
        if (request()->isAjax()) {
            $request = request();
            $Merchant = new Merchant();
            $Agent = new Agent();
            $WxOpen = new WxOpen();
            $map['id'] = $request->post('id');
            $config = $Merchant->where($map)->find();
            $agent = $Agent->where(array('id' => $config['agent']))->find();
            $users = $WxOpen->where(array('id' => $agent['wx_open_id']))->find();
            $userwx = $WxOpen->where(array('id' => $config['wx_open_id']))->find();
            $options = array(
                'appid' => $users['authorizer_appid'], // 填写高级调用功能的app id
                'partnerid' => $agent['partnerid'], // 财付通商户身份标识
                'partnerkey' => $agent['partnerkey'], // 财付通商户权限密钥Key
            );
            $weObj = new Wxobjopen($options);
            $appid = $users['authorizer_appid'];
            $mch_id = $agent['partnerid'];
            $out_trade_no = $request->post('orderid');
            $nonce_str = $weObj->generateNonceStr();
            $sub_mch_id = $config['sub_mch_id'];
            $sub_appid = $userwx['authorizer_appid'];
            $pay_xml = $weObj->createOrderXml($appid, $mch_id, $sub_appid, $sub_mch_id, $out_trade_no, $nonce_str);
            $payorder_xml = $weObj->getPayNum($pay_xml);
            $orderno = $payorder_xml['transaction_id'];
            $pay_zt = $payorder_xml['trade_state'];
            if ($pay_zt == "SUCCESS") {
                $array = array('code' => 0, 'message' => "充值成功");
            } else {
                $array = array('code' => 1, 'message' => "充值失败");
            }
            return json($array);
        }
    }

    //获取订单
    public function getorder2()
    {
        $request = request();
        if ($request->isAjax()) {
            $sh = $request->post('id');
            $order = "H" . $sh . "-" . date('YmdHis') . rand(10000, 99999);
            echo $order;
        }
    }


    //余额    查询该会员卡余额
    /*
     * $card_id
     *
     */
    public function balance($card_id='')
    {
        //获取传值
        $arr = request()->param();
        //解密code 获取用户信息
        if (isset($arr['encrypt_code'])){
            $this->getusercode($arr);
        }
        //获取授权
        $this->_init();
        $info = $this->getuserinfo($arr);
        $appid = $this->getappid($arr['card_id']);
        if ($info) {
            $arr = request()->param();
            $mab['openid'] = Session::get('card_openid');
            $mab['card_id'] = $info['card_id'];
            $mab['add_balance|del_balance']= ['neq', 0];
            $CardUserUpdate = new CardUserUpdate();
            $CardMember = new CardMember();
            $CardUserGet = new CardUserGet();
            $list = $CardUserUpdate->where($mab)->order('id desc')->select();

            $maps['card_id'] = $arr['card_id'];
            $maps['openid'] = Session::get($appid.'_openid');
            $maps['have'] = 1;
            $card['balance'] = $info['balance'];
            $card['brandname'] = $CardMember->where('card_id', $arr['card_id'])->value('brand_name');
            //JSSDK
            $share['wxjssdk'] = $this->getsharejssdk($card_id);
            $share['wxjssdk'] = json_encode($share['wxjssdk']);
            $this->assign('share',$share);
            $this->assign('card', $card);
            $this->assign('list', $list);
            $is_money = $CardMember->where('card_id', $arr['card_id'])->value('is_money');
            if ($is_money == 1) {
                return $this->fetch();
            } else {
                return $this->fetch('off');
            }
        } else {
            $data['card_id'] = $arr['card_id'];
            $data['openid'] = Session::get($appid.'_openid');
            $this->redirect('Carduser/addcard', $data);
        }
    }

    public function ci(){
        Session::clear();
    }

    //余额详情
    public function balancedetail(){
        $arr = request()->param();
        $map['id'] = $arr['dalanceid'];
        $map['card_id'] = $arr['card_id'];
        $map['add_balance|del_balance']= ['neq', 0];
        $CardUserUpdate = new CardUserUpdate();
        $info = $CardUserUpdate->where($map)->find();
        $this->assign('info',$info);
        return $this->fetch();
    }

    //积分    查询该会员卡积分
    /*
     * $card_id
     */
    public function bonus($card_id = '')
    {
//        $this->_init();
//        $arr = request()->param();
//        $map['openid'] = Session::get('card_openid');
//        if (empty($card_id)){
//            $map['card_id'] = $arr['card_id'];
//        }else{
//            $map['card_id'] = $card_id;
//        }
//        $map['card_type'] = 'MEMBER_CARD';
//        $map['have'] = 1;
//        $map['statu'] = 0;
//        $CardUserGet = new CardUserGet();
//        $info = $CardUserGet->where($map)->find();
        //获取传值
        $arr = request()->param();
        //解密code 获取用户信息
        if (isset($arr['encrypt_code'])){
            $this->getusercode($arr);
        }
        //获取授权
        $this->_init();
        $info = $this->getuserinfo($arr);
        if ($info) {
            $arr = request()->param();
            $mab['card_id'] = $arr['card_id'];
            $mab['openid'] = Session::get('card_openid');
            $mab['add_bonus|del_bonus'] = array('neq', 0);
            $CardUserUpdate = new CardUserUpdate();
            $CardUserGet = new CardUserGet();
            $CardMember = new CardMember();
            $list = $CardUserUpdate->where($mab)->order('id desc')->select();
            $maps['card_id'] = $arr['card_id'];
            $maps['openid'] = Session::get('card_openid');
            $card['bonus'] = $CardUserGet->where($maps)->value('bonus');
            $card['brandname'] = $CardMember->where('card_id', $arr['card_id'])->value('brand_name');
            //JSSDK
            $share['wxjssdk'] = $this->getsharejssdk($card_id);
            $share['wxjssdk'] = json_encode($share['wxjssdk']);
            $this->assign('share',$share);
            $this->assign('card', $card);
            $this->assign('list', $list);
            $is_bonus = $CardMember->where('card_id', $arr['card_id'])->value('is_bonus');
            if ($is_bonus == 1) {
                return $this->fetch();
            } else {
                return $this->fetch('off');
            }
        } else {
            $this->redirect('Carduser/weboff', ['card_id' => $card_id]);
        }
    }

    //余额
    //余额    查询该会员卡余额
    /*
     * $card_id
     *
     */
    public function balancelist($card_id='')
    {
//        $this->_init();
//        $arr = request()->param();
//        $map['openid'] = Session::get('card_openid');
//        if (empty($card_id)){
//            $map['card_id'] = $arr['card_id'];
//        }else{
//            $map['card_id'] = $card_id;
//        }
//        $map['card_type'] = 'MEMBER_CARD';
//        $map['have'] = 1;
//        $CardUserGet = new CardUserGet();
//        $info = $CardUserGet->where($map)->find();
        //获取传值
        $arr = request()->param();
        //解密code 获取用户信息
        if (isset($arr['encrypt_code'])){
            $this->getusercode($arr);
        }
        //获取授权
        $this->_init();
        $info = $this->getuserinfo($arr);
        if ($info) {
            $arr = request()->param();
            $mab['openid'] =  Session::get('card_openid');
            $mab['card_id'] = $info['card_id'];
            if ($arr['type'] == "recharge"){
                $mab['add_balance']= ['neq', 0];
            }elseif($arr['type'] == "consum"){
                $mab['del_balance']= ['neq', 0];
            }
            $CardUserUpdate = new CardUserUpdate();
            $CardMember = new CardMember();
            $CardUserGet = new CardUserGet();
            $list = $CardUserUpdate->where($mab)->order('id desc')->select();
            $maps['card_id'] = $arr['card_id'];
            $maps['openid'] = Session::get('card_openid');
            $maps['have'] = 1;
            $card['balance'] = $info['balance'];
            $card['brandname'] = $CardMember->where('card_id', $arr['card_id'])->value('brand_name');
            //JSSDK
            $share['wxjssdk'] = $this->getsharejssdk($card_id);
            $share['wxjssdk'] = json_encode($share['wxjssdk']);
            $this->assign('share',$share);
            $this->assign('card', $card);
            $this->assign('list', $list);
            $is_money = $CardMember->where('card_id', $arr['card_id'])->value('is_money');
            $url = "https://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
//            var_dump($url);
            if ($is_money == 1) {
                return $this->fetch();
            } else {
                return $this->fetch('off');
            }
        } else {
            $data['card_id'] = $arr['card_id'];
            $data['openid'] = Session::get('card_openid');
            $this->redirect('Carduser/addcard', $data);
        }
    }

    //等级
    /*
     * $card_id
     */
    public function level($card_id ='')
    {
        //获取传值
        $arr = request()->param();
        //解密code 获取用户信息
        if (isset($arr['encrypt_code'])){
            $this->getusercode($arr);
        }
        //获取授权
        $this->_init();
        $info = $this->getuserinfo($arr);
        if ($info) {
//            $arr = request()->param();
//            if (empty($arr['code'])) {
//                $map['openid'] = Session::get('card_openid');
//            }
//            $map['card_id'] = $arr['card_id'];
//            $CardUserGet = new CardUserGet();
            $CardRank = new CardRank();
//            $info = $CardUserGet->where($map)->find();
            //获取对应等级
            $maps['card_id'] = array('eq', $arr['card_id']);
            $level = $CardRank->where($maps)->select();
            //JSSDK
            $share['wxjssdk'] = $this->getsharejssdk($card_id);
            $share['wxjssdk'] = json_encode($share['wxjssdk']);
            $this->assign('share',$share);
            $this->assign('level', $level);
            $this->assign('info', $info);
            $CardMember = new CardMember();
            $is_rank = $CardMember->where('card_id', $card_id)->value('is_rank');
            if ($is_rank == 1) {
                return $this->fetch();
            } else {
                return $this->fetch('off');
            }
        } else {
            $this->redirect('Carduser/weboff', ['card_id' => $card_id]);
        }
    }

    //等级奖励领取
    /*
     * ajax 方式     gid  即该会员在数据表中的id
     * */
    public function getRankReward(){
        if (Request()->isAjax()){
            $arr = request()->post();      //获取参数
            $CardRank = new CardRank();
            $CardUserGet = new CardUserGet();
            $map['id'] = $arr['gid'];
            $user = $CardUserGet->where($map)->field('bonus,openid,code,card_id,rank_lock,balance')->find();  //会员信息
            $isarr['lid'] = $arr['lid'];
            $isarr['user_bonus'] = $user['bonus'];
//            return $isarr;
            $is_rank = $this->is_rank($isarr);      //等级判断
            if ($is_rank == 0){
                $rank = $CardRank->where(['id'=>$arr['lid']])->find();     //等级奖励
//                $level = getlive($user['card_id'],$user['bonus']);  //是否已领取
                if ($user['rank_lock'] < $rank['live']){
                    if ($rank['reward_bonus'] > 0 || $rank['reward_balance'] >0) {
                        $marke = new Cardmarke();
                        if ($rank['reward_bonus'] > 0){
                            $bonus['card_id'] = $user['card_id'];
                            $bonus['code'] = $user['code'];
                            $bonus['openid'] = $user['openid'];
                            $bonus['add_bonus'] = $rank['reward_bonus'];
                            $bonus['name'] = '等级奖励';
                            $bonus['outerstr'] = '等级奖励';
                            $resbonus = $marke->varybonus($bonus);
                        }else{
                            $resbonus = 0;
                        }
                        if ($rank['reward_balance'] > 0){
                            $balance['card_id'] = $user['card_id'];
                            $balance['code'] = $user['code'];
                            $balance['openid'] = $user['openid'];
                            $balance['add_balance'] = $rank['reward_balance'];
                            $balance['name'] = '等级奖励';
                            $balance['type'] = '3';
                            $balance['balance'] = $user['balance'] + $rank['reward_balance'];
                            $balance['outerstr'] = '等级奖励';
                            $resbalance = $marke->varybanlance($balance);
                        }else{
                            $resbalance = 0;
                        }
                        if ($resbalance == 0 && $resbonus == 0){
                            $ldata['rank_lock'] = $rank['live'];
                            $CardUserGet->save($ldata,$map);
                            $rarr['code'] = 0;
                            $rarr['message'] = '领取成功';
                        }else{
                            $rarr['code'] = 0;
                            $rarr['message'] = '领取失败';
                        }
                    }else{
                        $rarr['code'] = 9003;
                        $rarr['message'] = '无奖励';
                    }
                }else{
                    $rarr['code'] = 9002;
                    $rarr['message'] = '已领取';
                }
            }else{
                $rarr['code'] = 9001;
                $rarr['message'] = '未达到';

            }
            return json($rarr);
        }
    }

    //等级判断
    private function is_rank($arr){
        $CardRank = new CardRank();
        $map['id'] = $arr['lid'];
        $rank = $CardRank->where($map)->find();
        if ($rank['bonus'] <= $arr['user_bonus']){
            $data = 0;      //达到
        }else{
            $data = 1;      //未达到
        }
        return $data;
    }


    //我的卡券  查询所有属于该openid的会员卡
    /*
     * $card_id
     */
    public function mecard()
    {
        $this->_init();
        $arr = request()->param();
        $map['openid'] = Session::get('card_openid');
        $map['have'] = 1;
        $map['card_type'] = 'MEMBER_CARD';
        $CardMember = new CardMember();
        //我的会员卡
        $CardUserGet = new CardUserGet();
        //我的券
        $maps['openid'] = Session::get('card_openid');
        $maps['have'] = 1;
        $maps['card_type'] = array('neq', 'MEMBER_CARD');
        $maps['statu'] = ['neq', 2];
        $mevou = $CardUserGet->where($maps)->order('statu asc')->select();
        $this->assign('card',$arr);
        $this->assign('mevou', $mevou);
        $is_mecard = $CardMember->where('card_id', $arr['card_id'])->value('is_mecard');
        if ($is_mecard == 1) {
            return $this->fetch();
        } else {
            return $this->fetch('off');
        }
    }



    //适用门店
    /*
     * $card_id
     */
    public function storelist($card_id = '')
    {
        $arr = request()->param();
        //解密code 获取用户信息
        if (isset($arr['encrypt_code'])){
            $this->getusercode($arr);
        }
        //获取授权
        $this->_init();
        $info = $this->getuserinfo($arr);
        if ($info) {
            $CardMember = new CardMember();
            $Merchant = new Merchant();
            $top_mid = $CardMember->where('card_id', $card_id)->value('top_mid');
            $base_info = $CardMember->where('card_id', $card_id)->value('base_info');
            $base_info = json_decode($base_info, true);
            if ($base_info['use_all_locations'] == 'true') {
                $mab['top_mid'] = $top_mid;
            } else {
                $mapid = $base_info['location_id_list'];
                $mab['mapid'] = ['in', $mapid];
            }
            $storelist = $Merchant->where($mab)->select();
            $this->assign('list', $storelist);
            $is_locations = $CardMember->where('card_id', $card_id)->value('is_locations');
            if ($is_locations == 1) {
                return $this->fetch();
            } else {
                return $this->fetch('off');
            }
        } else {
            $this->redirect('Carduser/weboff', ['card_id' => $card_id]);
        }
    }

    //门店详情
    /*
     * 门店id
     * $id
     */
    public function storeinfo($id)
    {
        $Merchant = new Merchant();
        $MerchantContent = new MerchantContent();
        $map['id'] = $id;
        $info = $Merchant->where($map)->find();
        $info['phone'] = $MerchantContent->where('mid',$id)->value('tel');
        $this->assign('info', $info);
        return $this->fetch();
    }

    //会员卡详情
    /*
     * $card_id
     *
     */
    public function cardinfo($card_id ='')
    {
        $arr = request()->param();
        //解密code 获取用户信息
        if (isset($arr['encrypt_code'])){
            $this->getusercode($arr);
        }
        //获取授权
        $this->_init();
        $info = $this->getuserinfo($arr);
        if ($info) {
            $CardMember = new CardMember();
            $card = $CardMember->where('card_id', $card_id)->find();
            $card['base_info'] = json_decode($card['base_info'], true);
            $this->assign('card', $card);
            $is_card_info = $CardMember->where('card_id', $card_id)->value('is_card_info');
            if ($is_card_info == 1) {
                return $this->fetch();
            } else {
                return $this->fetch('off');
            }
        } else {
            $this->redirect('Carduser/weboff', ['card_id' => $card_id]);
        }
    }

    //修改资料
    /*
     * $card_id
     *
     */
    public function userinfo($card_id = '')
    {
        $arr = request()->param();
        //解密code 获取用户信息
        if (isset($arr['encrypt_code'])){
            $this->getusercode($arr);
        }
        //获取授权
        $this->_init();
        $info = $this->getuserinfo($arr);
        if ($info) {
            $map['card_id'] = $card_id;
            $map['openid'] = Session::get('card_openid');
            $CardUserGet = new CardUserGet();
            $info = $CardUserGet->where($map)->find();
            //JSSDK
            $share['wxjssdk'] = $this->getsharejssdk($arr['card_id']);
            $share['wxjssdk'] = json_encode($share['wxjssdk']);
            $this->assign('share',$share);
            //END
            $this->assign('info', $info);
            $CardMember = new CardMember();
            $is_edit_user = $CardMember->where('card_id', $card_id)->value('is_edit_user');
            if ($is_edit_user == 1) {
                return $this->fetch();
            } else {
                return $this->fetch('off');
            }
        } else {
            $this->redirect('Carduser/weboff', ['card_id' => $card_id]);
        }
    }

    //修改会员资料
    /*
     * $card_id
     *
     */
    public function editinfo()
    {
        $arr = request()->param();
        //解密code 获取用户信息
        if (isset($arr['encrypt_code'])){
            $this->getusercode($arr);
        }
        //获取授权
        $this->_init();
        $info = $this->getuserinfo($arr);
        if ($info) {
            $map['card_id'] = $arr['card_id'];
            //JSSDK
            $share['wxjssdk'] = $this->getsharejssdk($arr['card_id']);
            $share['wxjssdk'] = json_encode($share['wxjssdk']);
            $this->assign('share',$share);
            //END
            $this->assign('info', $info);
            return $this->fetch();
        } else {
            $this->redirect('Carduser/weboff', ['card_id' => $arr['card_id']]);
        }
    }

    //修改处理
    /*
     * $data['id'] $data['card_id']
     * POST 修改数据
     *
     */
    public function editinfohand(){
        if (Request()->isPost()){
            $data = request()->post();
            $map['id'] = $data['id'];
            $CardUserGet = new CardUserGet();
            $res = $CardUserGet->allowField(true)->save($data,$map);
            if ($res){
                $this->success('修改成功！',url('carduser/editinfo', ['card_id' => $data['card_id']]));
//                $rarr['code'] = 0;
//                $rarr['message'] = '修改成功！';
            }else{
                $this->error('修改失败！',url('carduser/editinfo', ['card_id' => $data['card_id']]));
//                $rarr['code'] = 9001;
//                $rarr['message'] = '修改失败';
            }
        }
    }

    //我的订单
    /*
     * $card_id
     *
     */
    public function orderme($card_id)
    {
        $arr = request()->param();
        //解密code 获取用户信息
        if (isset($arr['encrypt_code'])){
            $this->getusercode($arr);
        }
        //获取授权
        $this->_init();
        $info = $this->getuserinfo($arr);
        if ($info) {
            $mab['openid'] = Session::get('card_openid');
            $mab['card_id'] = $card_id;
            $CardOrder = new CardOrder();
            $list = $CardOrder->where($mab)->order('id desc')->select();
            $card['card_id'] = $card_id;
            $this->assign('list', $list);
            $this->assign('card',$card);
            return $this->fetch();
        } else {
            $this->redirect('Carduser/weboff', ['card_id' => $card_id]);
        }
    }

    //订单详情
    /*
     * 订单id 会员卡$card_id
     *
     * $id $card_id
     */
    public function orderinfo(){
        $arr = request()->param();
        //解密code 获取用户信息
        if (isset($arr['encrypt_code'])){
            $this->getusercode($arr);
        }
        //获取授权
        $this->_init();
        $info = $this->getuserinfo($arr);
        if ($info) {
            $mab['openid'] = Session::get('card_openid');
            $mab['card_id'] = $arr['card_id'];
            $mab['id'] = $arr['id'];
            $CardGoods = new CardGoods();
            $CardOrder = new CardOrder();
            $order = $CardOrder->where($mab)->find();
            $goods = $CardGoods->where('id',$order['gid'])->find();
            $this->assign('goods',$goods);
            $this->assign('order', $order);
            return $this->fetch();
        } else {
            $this->redirect('Carduser/weboff', ['card_id' => $arr['card_id']]);
        }
    }

    //功能开关   暂时弃用
    /*
     *  $arr['openid'] / $arr['card_id'] / $arr['is_dedu_cards']
     *
     */
    public function disetup(){
        if (Request()->isAjax()){
            $arr = request()->post();
            $CardUserGet = new CardUserGet();
            $map['openid'] = $arr['openid'];
            $map['card_id'] = $arr['card_id'];
            $map['have'] = 1;
            $map['card_type'] = 'MEMBER_CARD';
            $data['is_dedu_cards'] = $arr['is_dedu_cards'];
            $res = $CardUserGet->allowField('is_dedu_cards')->update($data,$map);
            if ($res){
                $rass['code'] = 0;
                $rass['message'] = '修改成功';
            }else{
                $rass['code'] = 9001;
                $rass['message'] = '修改失败';
            }
            return json($rass);
        }else{
            $this->_init();
            $arr = request()->param();
            $map['openid'] = Session::get('card_openid');
            $map['card_id'] = $arr['card_id'];
            $map['have'] = 1;
            $map['card_type'] = 'MEMBER_CARD';
            $CardUserGet = new CardUserGet();
            $info = $CardUserGet->where($map)->find();
            if ($info) {                                                                //会员信息
                $card['card_id'] = $arr['card_id'];
                $this->assign('info', $info);
                $this->assign('card',$card);
                return $this->fetch();
            } else {
                $this->redirect('Carduser/weboff', ['card_id' => $arr['card_id']]);        //关闭
            }
        }
    }

    //关闭页面 (jssdk 实现)
    /*
     * $card_id
     *
     */
    public function weboff($card_id)
    {
        //jssdk
        $url = "https://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
        $options = $this->options($card_id);
        $weObj = new Wxobjopen($options);
        $jssdk = $weObj->getJsSign($url);
        $this->assign('jssdk', $jssdk);
        return $this->fetch();
    }

    //打开卡
    /*
     * $card_id /
     *
     */
    public function opencard()
    {
        $this->_init();
        $card_id = request()->param('card_id');
        $openid = Session::get('card_openid');
        $CradUserGet = new CardUserGet();
        $info = $CradUserGet->where(['card_id' => $card_id, 'openid' => $openid, 'have' => '1', 'statu' => 0])->find();
        if ($info) {
            $card['card_id'] = $card_id;
            $card['code'] = $info['code'];
            $url = "https://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
            $options = $this->options($card_id);
            $weObj = new Wxobjopen($options);
            $jssdk = $weObj->getJsSign($url);
            $this->assign('jssdk', $jssdk);
            $this->assign('card', $card);
            return $this->fetch();
        } else {
            $data['card_id'] = $card_id;
            $data['openid'] = $openid;
            $this->redirect(url('carduser/addcard', $data));
        }
    }

    //发放卡
    /*
     * $arr['openid'] / $arr['card_id']
     *
     *
     */
    public function addcard()
    {
//        $this->_init();
        $arr = request()->param();
        if (isset($arr['openid']) && isset($arr['card_id'])) {
            $url = "https://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
            $options = $this->options($arr['card_id']);
            //发放
            $arrs['card_id'] = $arr['card_id'];
            $arrs['openid'] = $arr['openid'];
            $weObj = new Wxobjopen($options);
            $card = $this->put($arrs);
            $jssdk = $weObj->get_card_JsSign($url);
            $jssdk['url'] = $url;
            $this->assign('card', $card);
            $this->assign('jssdk', $jssdk);
            return $this->fetch();
        }
    }

    //发放卡
    /*
     *
     *
     */
    public function addcardmicro()
    {
        $this->_init();
        $card_id = request()->param('card_id');
        $openid = Session::get('card_openid');
        if (isset($openid) && isset($card_id)) {
            $url = "https://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
            $options = $this->options($card_id);
            //发放
            $arrs['card_id'] = $card_id;
            $arrs['openid'] = $openid;
            $weObj = new Wxobjopen($options);
            $card = $this->put($arrs);
            $jssdk = $weObj->get_card_JsSign($url);
            $jssdk['url'] = $url;
            $this->assign('card', $card);
            $this->assign('jssdk', $jssdk);
            return $this->fetch();
        }
    }


    //AJax打开卡
    /*
     * $arr['card_id'] , $arr['url']
     *
     */
    public function getopencard(){
        if (Request()->isAjax()){
            $arr = request()->post();
            $card_id = $arr['card_id'];
            $openid = Session::get('card_openid');
            $CradUserGet = new CardUserGet();
            $map['openid'] = $openid;
            $map['card_id'] = $card_id;
            $map['have'] = 1;
            $map['statu'] = 0;
            $info = $CradUserGet->where(['card_id' => $card_id, 'openid' => $openid, 'have' => '1', 'statu' => 0])->find();
            if ($info) {
                $url = $arr['url'];
                $options = $this->options($card_id);
                $weObj = new Wxobjopen($options);
                $jssdk = $weObj->getJsSign($url);
                //输出内容
                $card['jssdk']['debug'] = true;
                $card['jssdk']['appId'] = $jssdk['appId'];
//                $card['jssdk']['api_ticket'] = $jssdk['ticket'];
//                $card['jssdk']['url'] = $jssdk['url'];
                $card['jssdk']['timestamp'] = $jssdk['timestamp'];
                $card['jssdk']['nonceStr'] = $jssdk['nonceStr'];
                $card['jssdk']['signature'] = $jssdk['signature'];
                $card['jssdk']['jsApiList'] = ['hideAllNonBaseMenuItem','openCard'];
                $card['card']['cardId'] = $card_id;
                $card['card']['code'] = $info['code'];
                return json($card);
            } else {
                $data['code'] =  9001;
                $data['msg'] = '没有此卡，请先领取！';
                return json($data);
            }
        }
    }

    //Ajax打开领取
    /*
     * $arr['card_id']
     */
    public function getaddcard(){
        if (Request()->isAjax()){
            $arr = request()->post();
            $url = "https://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
            $options = $this->options($arr['card_id']);
            //发放
            $arrs['card_id'] = $arr['card_id'];
            $arrs['openid'] = Session::get('card_openid');
            $weObj = new Wxobjopen($options);
            $jssdk = $weObj->get_card_JsSign($url);
            //输出内容
            $card['card'] = $this->put($arrs);
            $card['jssdk']['debug'] = false;
            $card['jssdk']['api_ticket'] = $jssdk['ticket'];
            $card['jssdk']['url'] = $jssdk['url'];
            $card['jssdk']['appId'] = $jssdk['appId'];
            $card['jssdk']['timestamp'] = $jssdk['timestamp'];
            $card['jssdk']['nonceStr'] = $jssdk['nonceStr'];
            $card['jssdk']['signature'] = $jssdk['signature'];
            $card['jssdk']['jsApiList'] = ['penCard','addCard'];
            return json($card);
        }
    }

    //发放卡列表
    /*
     * $arr['openid'] / $arr['give'] /
     *
     */
    public function addcardlist()
    {
        $this->_init();
        $arr = request()->param();
        if (isset($arr['openid']) && isset($arr['give'])) {
            if ($arr['openid'] == Session::get('card_openid')) {
                $CardCzgive = new CardCzgive();
                $card_id = $CardCzgive->where('id', $arr['give'])->value('zs_card_id');
                $cardlist = explode(',', $card_id);
                foreach ($cardlist as $k => $v) {
                    if (filteroffcard($v) == true) {
                        $options = $this->options($v);
                        $arrs['card_id'] = $v;
                        $arrs['openid'] = $arr['openid'];
                        $card[$k] = $this->putlist($arrs);
                    }
                }
                if(isset($options)){
                    $weObj = new Wxobjopen($options);
                    $url = "https://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
                    $jssdk = $weObj->getJsSign($url);
                    $this->assign('card', json_encode($card));
                    $this->assign('jssdk', $jssdk);
                    return $this->fetch();
                }
                else{
                    $this->error("该卡券已过期");
                }
            }else{
                $CardCzgive = new CardCzgive();
                $card_id = $CardCzgive->where('id', $arr['give'])->value('card_id');
                $this->redirect('Carduser/weboff', ['card_id' => $card_id]);
            }
        }
    }

    //批量投放
    /*
     * $arr['openid'] / $arr['card_id']
     */
    private function putlist($arr){
        $options = $this->options($arr['card_id']);
        $weObj = new Wxobjopen($options);
        $noncestr = $weObj->generateNonceStr();
        $res['cardId'] = $arr['card_id'];
        $res['cardExt'] = $weObj->wxAddCard($arr['openid'], $arr['card_id'], $noncestr);
        return $res;
    }

    //投放卡
    /*
     * $arr['openid'] / $arr['card_id']
     */
    private function put($arr)
    {
        $options = $this->options($arr['card_id']);
        $weObj = new Wxobjopen($options);
        $noncestr = $weObj->generateNonceStr();
        $outer_str = 'CardCenter';
        $res['card_id'] = $arr['card_id'];
        $res['addcard'] = $weObj->wxAddCard($arr['openid'], $arr['card_id'], $noncestr,$outer_str);
        return $res;

    }

    //获取该门店所属商户的所有下属门店
    /*
     * $mid
     */
    private function getmidlist($mid){
        $Merchant = new Merchant();
        $top_mid = $Merchant->where('id',$mid)->value('top_mid');
        $midlist = $Merchant->where(['top_mid' => $top_mid])->field('id')->select();
        $smid=[];
        foreach ($midlist as $k => $v) {
            $smid[] = $v['id'];
        }
        $mids = implode(',', $smid);
        return $mids;
    }

    /* 获取创建该卡券的门店id
     *
     * $card_id
     *
     */
//    private function getmid($card_id)
//    {
//        $CardMember = new CardMember();
//        $CardGeneral = new CardGeneral();
//        $top_mid = $CardMember->where(['card_id' => $card_id])->value('mid');
//        if (empty($top_mid)) {
//            $top_mid = $CardGeneral->where(['card_id' => $card_id])->value('mid');
//            return $top_mid;
//        } else {
//            return $top_mid;
//        }
//    }



    //分享jssdk
    /*
     * $card_id
     * 
     */
    private function getsharejssdk($arr){
        $url = "https://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
        $options = $this->options($arr);
        //分享
        $weObj = new Wxobjopen($options);
        $jssdk = $weObj->getJsSign($url);
        $wxJsSdk = [
            'debug' => false,
            'appId' => $jssdk['appId'],
            'timestamp' =>$jssdk['timestamp'],
            'nonceStr' => $jssdk['nonceStr'],
            'signature' => $jssdk['signature'],
            'jsApiList' => [
                'onMenuShareTimeline',
                'onMenuShareAppMessage',
                'onMenuShareQQ',
                'onMenuShareQZone',
                'closeWindow',
                'hideAllNonBaseMenuItem',
            ]
        ];
        return $wxJsSdk;
    }
    public function test(){
        echo request()->domain();
        exit();
        $s=getgivecardnew('[{"zs_card_id":"pCVCLv0Z2UNmnrRcoC2bamHpj0EY","zs_no":"2"}]',0);
   var_dump($s);
    }


}
